package 算法.leetcode.linked.list;

import org.junit.Test;

/**
 * @author lchenglong
 * @date 2021/1/4
 */
public class RemoveNthFromEnd extends LinkListBase{

    @Test
    public void test() {
        int[] arr = new int[]{1,2,3,4,5};
        ListNode head = createTestData(arr);
        ListNode node = removeNthFromEnd(head, 2);
        toString(node);
    }
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode fast = head,slow = head,dummy = new ListNode(-1);
        // 用来解决头结点的问题
        dummy.next = head;
        ListNode pre = dummy;
        for (int i=0;i<n;i++) {
            fast = fast.next;
        }

        while (fast!=null) {
            fast = fast.next;
            slow = slow.next;
            pre = pre.next;
        }
        pre.next = slow.next;
        return dummy.next;
    }
}
